<template>
  <n-modal
    :title="`分配 ${user?.username} 的菜单权限`"
    v-model:show="show"
    preset="card"
    :show-icon="false"
    max-w-900
    size="huge"
  >
    <n-space mb-10>
      <n-tag
        type="info"
        v-for="id in checkedRolesId"
        :key="id"
        closable
        @close="
          checkedRolesId = checkedRolesId.filter((roleId) => roleId !== id)
        "
      >
        {{ tableData.find((data) => data.id === id)?.name }}
      </n-tag>
    </n-space>
    <data-table
      v-model:checked-keys="checkedRolesId"
      :row-key="(row) => row.id"
      :columns="columns"
      :request="getRoleList"
      @update:data="(data) => (tableData = data)"
    ></data-table>
    <template #footer>
      <n-space justify="end">
        <n-button :loading="btnLoading" @click="getUsersRoles(user?.id)">
          重置
        </n-button>
        <n-button type="primary" :loading="btnLoading" @click="handleSubmit">
          提交
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { roleApi, sysUserApi } from "@/api";
import { useTableColumns } from "./common";

const props = defineProps<{ user?: User }>();

const show = ref(false);
const btnLoading = ref(false);
const tableData = ref<Role[]>([]);
const checkedRolesId = ref<string[]>([]);
const { columns } = useTableColumns();

const getUsersRoles = async (userId?: string) => {
  if (!userId) return;
  const { status, data } = await sysUserApi.getRolesIdById(userId);
  if (!status) return;
  checkedRolesId.value = data;
};

const getRoleList = async () => {
  const { status, data } = await roleApi.getList();
  if (!status) return;
  return data;
};

watch(
  () => props.user?.id,
  (newV) => {
    if (newV) getUsersRoles(newV);
  },
  { immediate: true }
);

const handleSubmit = async () => {
  if (!props.user?.id) return;
  btnLoading.value = true;
  try {
    const { status } = await sysUserApi.assign({
      userId: props.user.id,
      roleIds: checkedRolesId.value,
    });
    if (status) {
      show.value = false;
      window.$message.success("分配成功");
    }
  } finally {
    btnLoading.value = false;
  }
};

const funShow = () => (show.value = true);
defineExpose({ show: funShow });
</script>
